package com.tc.biz.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tc.activiti.util.BeanUtils;
import com.tc.activiti.util.user.UserUtil;
import com.tc.base.constants.PageConstants;
import com.tc.base.constants.StateEnum;
import com.tc.base.entity.APIRequest;
import com.tc.base.entity.APIResult;
import com.tc.biz.entity.BpmnCopyProcess;
import com.tc.biz.entity.SysUser;
import com.tc.biz.service.BpmnApprovalService;
import com.tc.biz.service.BpmnCopyProcessService;
import com.tc.biz.service.IDrainagePipeMainService;
import com.tc.biz.service.IUserService;
import com.tc.biz.provider.BpmnBusinessProvider;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.identity.User;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zengqingfa
 * @date 2019/11/6 15:46
 * @description
 * @email zengqingfa_java@163.com
 */

@Api(tags = "抄送管理", value = "抄送管理")
@RestController
@RequestMapping("/bpmn/receive")
public class ReceiverProcessController {

    protected static final Logger logger = LoggerFactory.getLogger(ReceiverProcessController.class);

    @Autowired
    protected BpmnCopyProcessService processService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected IDrainagePipeMainService drainagePipeMainService;

    @Autowired
    protected IUserService userService;

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected BpmnApprovalService bpmnApprovalService;

    @Autowired
    protected BpmnBusinessProvider bpmnBusinessProvider;

    /**
     * 查询抄送的流程
     *
     * @param request
     * @param servletRequest
     * @return
     */
    @ApiOperation(value = "通过用户id查询抄送的流程", notes = "通过用户id查询抄送的流程")
    @RequestMapping(value = "/findByUserId", method = RequestMethod.POST)
    public APIResult findByUserId(@RequestBody(required = true) APIRequest request, HttpServletRequest servletRequest) {
        APIResult result = new APIResult<>();
        List<Map<String, Object>> listMap = new ArrayList<>();
        try {
            Integer pageSize = request.getRequestPage().getLimit();
            Integer pageNo = request.getRequestPage().getPageNo();
            //根据传递的参数userId查询当前登录人被抄送的流程
            String userId = request.getParameter("userId");
            SysUser sysUser1 = userService.selectByPrimaryKey(new Long(userId));
            if (BeanUtils.isEmpty(sysUser1)) throw new RuntimeException("用户不存在");
            //TODO 后续需要修改
            if (BeanUtils.isEmpty(userId)) {
                User user = UserUtil.getUserFromSession(servletRequest.getSession());
                // 用户未登录不能操作，实际应用使用权限框架实现，例如Spring Security、Shiro等
                if (user == null || StringUtils.isBlank(user.getId())) {
                    throw new RuntimeException("用户未登录，请登录再操作");
                }
            }
            if (pageNo == null) pageNo = PageConstants.DEFAULT_PAGE_NO;
            if (pageSize == null) pageSize = PageConstants.DEFAULT_PAGE_SIZE;
            //分页  抄送的流程
            PageHelper.startPage(pageNo, pageSize);
            List<BpmnCopyProcess> processList = processService.findByUserId(userId);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (BeanUtils.isNotEmpty(processList)) {
                for (BpmnCopyProcess receiverProcess : processList) {
                    String processInstanceId = receiverProcess.getProcessInstanceId();
                    HistoricProcessInstance processInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).orderByProcessInstanceStartTime().singleResult();
                    if (BeanUtils.isNotEmpty(processInstance)) {
                        Map<String, Object> values = new HashMap<>();
                        values.put("processInstance", processInstance);
                        //发起人
                        String startUserId = drainagePipeMainService.getStartedByProcessInstanceId(processInstanceId);
                        SysUser sysUser = userService.selectByPrimaryKey(new Long(startUserId));
                        values.put("startByUser", sysUser);
                        //创建时间
                        values.put("createTime", sdf.format(receiverProcess.getCreateTime()));
                        values.put("receiverProcess", receiverProcess);
                        //各个已审批流程的信息
                        List<HistoricTaskInstance> list = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstanceId).list();
                        //封装各个节点的信息
                        List<HashMap<String, Object>> taskDetailList = bpmnBusinessProvider.getTaskDetail(list);
                        values.put("taskDetailList", taskDetailList);
                        listMap.add(values);
                    }
                }
            }
            PageInfo pageInfo = new PageInfo(listMap);
            result.setData(pageInfo);
            result.setMessage("查询抄送的流程成功");
        } catch (Exception e) {
            result.setState(StateEnum.ERROR_BPMN.getCode());
            result.setMessage(StateEnum.ERROR_BPMN.getText());
            result.setCause(e.getMessage());
            logger.error("/bpmn/receive/findByUserId", e);
        }
        return result;
    }


}
